// https://f2.antv.vision/zh/examples/line/multiple#series

import F2 from '@antv/f2';
import _ from 'lodash';

fetch('../data/series-line.json')
  .then(res => res.json())
  .then(
    (
      data: Array<{
        type: string;
        date: string;
        value: number;
      }>,
    ) => {
      const chart = new F2.Chart<typeof data[0]>({
        id: 'container',
        pixelRatio: window.devicePixelRatio,
      });
      chart.source(data);
      chart.scale('date', {
        type: 'timeCat',
        tickCount: 3,
      });
      chart.scale('value', {
        tickCount: 5,
      });
      chart.axis('date', {
        label: function label(text, index, total) {
          // 只显示每一年的第一天
          const textCfg: F2.AxisLabelParams = {};
          if (index === 0) {
            textCfg.textAlign = 'left';
          } else if (index === total - 1) {
            textCfg.textAlign = 'right';
          }
          return textCfg;
        },
      });
      chart.tooltip({
        custom: true, // 自定义 tooltip 内容框
        onChange: function onChange(obj) {
          const legend = chart.get('legendController').legends.top![0];
          const tooltipItems = obj.items;
          const legendItems = legend.items;
          const map: Record<string, F2.LegendItem> = {};
          legendItems.forEach(function (item) {
            map[item.name] = _.clone(item);
          });
          tooltipItems.forEach(function (item) {
            const name = item.name!;
            const value = item.value;
            if (map[name]) {
              map[name].value = value;
            }
          });
          legend.setItems(_.values(map));
        },
        onHide: function onHide() {
          const legend = chart.get('legendController').legends.top![0];
          legend.setItems(chart.getLegendItems().type!);
        },
      });
      chart.line().position(['date', 'value']).color('type');
      chart.render();
    },
  );
